package com.woniuxy.project115.kaer.commons.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

//JWT工具类
public class  JwtUtil {
    //自定义的秘钥
    //HS256：即字节长度>=32
   static String sect = "ksaasfdasdfadsfwfrasdfsadffcasijfasadfasfdlkfjlasjflksajfd";

    //生成token
    //键值对包含用户信息
    //以分钟为单位的时间 代表jwt的有效时间
    public static String createToken(Map<String, Object> body, Integer mil) {
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.builder()
                .setClaims(body)
                .setExpiration(new Date(System.currentTimeMillis() + mil * 60 * 1000))
                .signWith(key)
                .compact();
    }

    //解析token
    public static Claims parseToken(String token) {
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.parserBuilder().setSigningKey(key)
                .build().parseClaimsJws(token).getBody();
    }
    //根据token获取用户id
    public static Integer getUserId(String token) throws Exception {
        Integer userId = parseToken(token).get("userId", Integer.class);
        if (userId == null) {
            throw new Exception("token解析失败");
        }
        return userId;
    }

    //根据token获取店铺id
    public static Integer getStoreId(String token) throws Exception {
        Integer storeId = parseToken(token).get("storeId", Integer.class);
        if (storeId == null) {
            throw new Exception("token解析失败");
        }
        return storeId;
    }

    //根据token获取用户名
    public static String getUserName(String token) throws Exception {
        String userName = parseToken(token).get("userName", String.class);
        if (userName == null) {
            throw new Exception("token解析失败");
        }
        return userName;
    }

    //根据token获取商家id
    public static Integer getTenantInfoId(String token) throws Exception {
        Integer tenantInfoId = parseToken(token).get("tenantInfoId", Integer.class);
        if (tenantInfoId == null) {
            throw new Exception("token解析失败");
        }
        return tenantInfoId;
    }
}